
<template>
  <span>
    <a-switch v-bind="$attrs" :checked="checked" @change="handleSwitchChange" />
  </span>
</template>
<script>
export default {
  name: 'CustomSwitch',
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    value: {
      type: [String, Number, Boolean],
    },
    checkedValue: {
      type: [String, Number, Boolean],
      default: '',
    },
    unCheckedValue: {
      type: [String, Number, Boolean],
      default: '',
    },
  },
  data() {
    return {
      checked: false,
    }
  },
  watch: {
    value: {
      handler(newValue, _) {
        this.initCheckedStatus(newValue)
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    initCheckedStatus(value) {
      const { checkedValue, unCheckedValue } = this
      let checked = value
      if (checkedValue !== '' && unCheckedValue !== '') {
        if (checkedValue === unCheckedValue) console.warn('checkedValue不能与unCheckedValue 相同')
        checked = checkedValue === value && unCheckedValue !== value
      }
      this.checked = checked
    },
    handleSwitchChange(e) {
      const { checkedValue, unCheckedValue } = this
      this.checked = e
      if (checkedValue !== '' && unCheckedValue !== '') return this.$emit('change', e ? checkedValue : unCheckedValue)
      this.$emit('change', e)
    },
  },
}
</script>
